﻿using Microsoft.Extensions.Hosting;
using MiniCap.Storage;
using MiniCap.Transport;

namespace MiniCap.Workers
{
    public class OutboxDispatcherService : BackgroundService
    {
        private readonly MySqlOutboxStorage _storage;
        private readonly RabbitMqTransport _transport;

        public OutboxDispatcherService(MySqlOutboxStorage storage, RabbitMqTransport transport)
        {
            _storage = storage;
            _transport = transport;
        }

        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {
            while (!stoppingToken.IsCancellationRequested)
            {
                var rows = await _storage.FetchPendingAsync(10);

                foreach (var row in rows)
                {
                    await _transport.PublishAsync(row.Topic, row.Body ?? "");
                    await _storage.MarkSentAsync(row.Id);
                }

                await Task.Delay(1000, stoppingToken);
            }
        }
    }
}
